import { toNumber } from 'lodash-es';
import { useClipboard } from '@vueuse/core';
import { ElMessage } from 'element-plus';

/**
 * 复制
 */
const { copy } = useClipboard();
export const copyText = (text:any) => {
  if (navigator.clipboard) {
    copy(text);
  } else {
    const input = document.createElement('input');
    input.setAttribute('value', text);
    document.body.appendChild(input);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);
  }
  ElMessage.success('复制成功');
};

/**
 * 生成随机字符串
 */
export function toAnyString() {
  const str: string = 'xxxxx-xxxxx-4xxxx-yxxxx-xxxxx'.replace(/[xy]/g, (c: string) => {
    const r: number = (Math.random() * 16) | 0;
    const v: number = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString();
  });
  return str;
}

/**
 * 首字母大写
 */
export function firstUpperCase(str: string) {
  return str.toLowerCase().replace(/( |^)[a-z]/g, (L) => L.toUpperCase());
}

export const generateUUID = () => {
  if (typeof crypto === 'object') {
    if (typeof crypto.randomUUID === 'function') {
      return crypto.randomUUID();
    }
    if (typeof crypto.getRandomValues === 'function' && typeof Uint8Array === 'function') {
      const callback = (c: any) => {
        const num = Number(c);
        return (num ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (num / 4)))).toString(
          16
        );
      };
      return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, callback);
    }
  }
  let timestamp = new Date().getTime();
  let performanceNow =
    (typeof performance !== 'undefined' && performance.now && performance.now() * 1000) || 0;
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    let random = Math.random() * 16;
    if (timestamp > 0) {
      random = (timestamp + random) % 16 | 0;
      timestamp = Math.floor(timestamp / 16);
    } else {
      random = (performanceNow + random) % 16 | 0;
      performanceNow = Math.floor(performanceNow / 16);
    }
    return (c === 'x' ? random : (random & 0x3) | 0x8).toString(16);
  });
};

/**
 * element plus 的文件大小 Formatter 实现
 *
 * @param row 行数据
 * @param column 字段
 * @param cellValue 字段值
 */
// @ts-ignore
export const fileSizeFormatter = (row, column, cellValue) => {
  const fileSize = cellValue;
  const unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const srcSize = parseFloat(fileSize);
  const index = Math.floor(Math.log(srcSize) / Math.log(1024));
  const size = srcSize / Math.pow(1024, index);
  const sizeStr = size.toFixed(2); //保留的小数位数
  return sizeStr + ' ' + unitArr[index];
};

/**
 * 将值复制到目标对象，且以目标对象属性为准，例：target: {a:1} source:{a:2,b:3} 结果为：{a:2}
 * @param target 目标对象
 * @param source 源对象
 */
export const copyValueToTarget = (target: any, source: any) => {
  const newObj = Object.assign({}, target, source);
  // 删除多余属性
  Object.keys(newObj).forEach((key) => {
    // 如果不是target中的属性则删除
    if (Object.keys(target).indexOf(key) === -1) {
      delete newObj[key];
    }
  });
  // 更新目标对象值
  Object.assign(target, newObj);
};

/**
 * 获取链接的参数值
 * @param key 参数键名
 * @param urlStr 链接地址，默认为当前浏览器的地址
 */
export const getUrlValue = (key: string, urlStr: string = typeof window !== 'undefined' ? window.location.href : ''): string => {
  if (!urlStr || !key) return '';
  try {
    // 使用 URL 构造函数的浏览器兼容性检查
    if (typeof window !== 'undefined' && window) {
      const url = new URL(decodeURIComponent(urlStr));
      return url.searchParams.get(key) ?? '';
    }
    // 降级方案：手动解析 URL 参数
    const queryStart = urlStr.indexOf('?');
    if (queryStart === -1) return '';
    const query = urlStr.slice(queryStart + 1);
    const params = new URLSearchParams(query);
    return params.get(key) ?? '';
  } catch (error) {
    console.warn('Failed to parse URL:', error);
    return '';
  }
};

/**
 * 获取链接的参数值（值类型）
 * @param key 参数键名
 * @param urlStr 链接地址，默认为当前浏览器的地址
 */
export const getUrlNumberValue = (key: string,urlStr: string = typeof window !== 'undefined' ? window.location.href : ''): number => {
  return toNumber(getUrlValue(key, urlStr));
};

// ========== NumberUtils 数字方法 ==========

/**
 * 数组求和
 *
 * @param values 数字数组
 * @return 求和结果，默认为 0
 */
export const getSumValue = (values: number[]): number => {
  return values.reduce((prev, curr) => {
    const value = Number(curr);
    if (!Number.isNaN(value)) {
      return prev + curr;
    } else {
      return prev;
    }
  }, 0);
};

/**
 * 计算环比
 *
 * @param value 当前数值
 * @param reference 对比数值
 */
export const calculateRelativeRate = (value?: number, reference?: number) => {
  // 防止除0
  if (!reference || reference === 0) return 0;

  return ((100 * ((value || 0) - reference)) / reference).toFixed(0);
};

/**
 * 截取字符串
 *
 * @param name
 * @param start
 * @param end
 */

export const sliceName = (name: string, start: number, end: number) => {
  if (name.length > end) {
    return name.slice(start, end);
  }
  return name;
};

/**
 * 替换对象中的空值（null、undefined、''）为 '--'
 * @param {Object} obj - 需要处理的对象
 * @returns {Object} - 处理后的对象
 */
const replaceEmptyValues = (obj: any) => {
  const newObj = {} as any;
  for (const key in obj) {
    if (Object.hasOwnProperty.call(obj, key)) {
      if (typeof obj[key] === 'object' && !Array.isArray(obj[key]) && obj[key] !== null) {
        // 如果是对象，递归处理
        newObj[key] = replaceEmptyValues(obj[key]);
      } else {
        // 如果是基本类型，替换空值
        newObj[key] =
          key !== 'ownerUserId' && (obj[key] === null || obj[key] === undefined || obj[key] === '')
            ? '--'
            : obj[key];
      }
    }
  }
  return newObj;
};

/**
 * 处理数组中的每个对象，替换空值为 '--'
 * @param {Array} data - 需要处理的数组
 * @returns {Array} - 处理后的数组
 */
export const processArray = (data: any[]) => {
  return data?.map((item) => replaceEmptyValues(item));
};
